import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/refreshable_layout.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';

class TaskListPage extends StatefulWidget {
  int status;
  String waybillNo;
  int isKa;
  TaskListPage(this.status,this.waybillNo,this.isKa, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return TaskListPageState();
  }
}

class TaskListPageState extends State<TaskListPage> {
  final RefreshableLayoutController _recyclerLayoutController = RefreshableLayoutController();
  late StreamSubscription _eventFn;
  List list = ["无人车未及时到达站点","订单紧急，车辆不足三轮车接单","商家/操作员填错地址","叫车数量超过实际用车数量","买家退货","装货物流车已走未装上车","操作员未及时到达站点","天气原因（大雨淋湿货物）"];
  int num =0;
  int total = 0;
  // int totalAll = 0;
  int cancelTotal = 0;
  int currentActiveIndex = 1;
  bool isChecked = false;

  @override
  void initState() {
    super.initState();
    _recyclerLayoutController.reload();
    _eventFn = eventBus.on<ChangeStationsEvent>().listen((event) {
      _recyclerLayoutController.reload();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: UIColor.color_main,
      child: Column(
        children: [
          _renderTitle(),
          Container(height: 1, color: Colors.black12),
          RefreshableLayout(
            urlCallback: _buildUrl,
            itemBuilder: _renderListItem,
            dataCallback: _dataCallback,
            controller: _recyclerLayoutController,
          ).expand,
          16.wspace,
        ],
      ),
    );
  }

  _dataCallback(dynamic data) {
    //cancelTotal = 0;
    if( data["page"]["page"] ==1){
      total = 0;
      cancelTotal = 0;
    }
    total =  data["list"].length+total;
   // totalAll = data["list"]data["list"].length  + totalAll;
    for(var i = 0; i<data["list"].length; i++)
      {
        if(data["list"][i]["status"] == 20){
          cancelTotal += 1;
        }
      }
  }

  String _buildUrl() {
    var baseUrl = "/waybill_mission/list?waybill_no=${widget.waybillNo}";
    return baseUrl;
  }

  Widget _renderTitle() {
    return Container(
      color: UIColor.color_content,
      width: double.infinity,
      height: MediaQuery.of(context).padding.top + 44.rpx,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child:Stack(
        children: [
          SizedBox(width: 50.rpx, child: IconButton(
            iconSize: 18.rpx,
            icon: const Icon(
              Icons.arrow_back_ios_new,
              color: UIColor.color_t1,
            ),
            onPressed: () {
              Navigator.of(context).pop();
              eventBus.fire(RefreshOrderEvent());
            },
          ),),
          Center(
              child: UText.get("任务列表", Colors.black, 16.rpx, fw: FontWeight.w600).center
          ),
          widget.isKa == 1 && widget.status == 2 ? Positioned(
              right: 20,
              bottom: 12,
              child: GestureDetector(
                onTap: () {
                  _onClickSubmit();
                },
                child: Text(
                  '新增任务',
                  style: TextStyle(
                    fontSize: 16.rpx,
                    color: UIColor.color_primary,
                    decorationColor: UIColor.color_primary,
                  ),
                ),
              )
          ):0.wspace,
        ],
      ),
    );
  }

  Widget _renderListItem(dynamic data, int index) {
    var st = data["status"];
    var missionStatus = data["mission_status"];
    dynamic widget,bgColor,color,name;
    if (st == 0 || st ==1) {
      bgColor = const Color(0xffED7B2F);
      color = UIColor.color_content;
      name = "未分配";
    } else if (st == 3) {
      if (missionStatus == 1 || missionStatus == 2 || missionStatus == 3){
        bgColor = const Color(0xff00A870);
        color = UIColor.color_content;
        name = "待装货";
      }
      if (missionStatus == 5 || missionStatus == 6 || missionStatus == 7){
        bgColor = const Color(0xff00A870);
        color = UIColor.color_content;
        name = "待卸货";
      }
    } else if (st == 4 || st == 5) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t9;
      name = "已完成";
    } else if (st == 20) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t7;
      name = "已取消";
    } else {
      return widget = 0.wspace;
    }
    widget = Container(
      width: 66.rpx,
      height: 32.rpx,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: const BorderRadius.only(topLeft:Radius.circular(60),bottomLeft:Radius.circular(60)),
      ),
      child: UText.get(name, color, 14.rpx),
    );
    return Row(
        children: [
          Container(
            width: 312.rpx,
            decoration: BoxDecoration(
              color: UIColor.color_content,
              borderRadius: BorderRadius.circular(12.rpx),
            ),
            margin: EdgeInsets.only(left: 15.rpx, right: 15.rpx, top: 10.rpx),
            padding: EdgeInsets.only(left: 13.rpx, top: 16.rpx, bottom: 16.rpx),
            child: Row(
              children: [
                Column(
                  children: [
                    UText.get("任务${data["no"]}", UIColor.color_t10, 14.rpx),
                    data["car_no"] == ""?0.wspace:
                    4.hspace,
                    SizedBox(
                      width: 210.rpx,
                      child:  UText.get(data["car_no"], UIColor.color_primary, 14.rpx,textAlign:TextAlign.left),
                    )
                  ],
                ),
                const Spacer(),
                widget
              ],
            ),
          ),
           GestureDetector(
              onTap: () {
                currentActiveIndex = 0;
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                    return StatefulBuilder(
                        builder: (BuildContext context,void Function(void Function()) setState) {
                          return
                              Dialog(
                              backgroundColor:Colors.transparent,
                              child: Container(
                                      width: 320.rpx,
                                      height: 510.rpx,
                                      decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
                                  ),
                                  child: Column(
                                      children: [
                                        24.hspace,
                                        UText.get("取消任务", UIColor.color_black, 16.rpx,fw: FontWeight.bold),
                                        16.hspace,
                                        Container( height: 0.5.rpx, color: UIColor.color_divider),
                                        ListBody(children:
                                            list.asMap().keys.map((index) =>
                                            GestureDetector(
                                                onTap: (){
                                                  setState(() {
                                                    currentActiveIndex = index;
                                                  });
                                                },
                                                child: Container (
                                                    padding: EdgeInsets.only(left:0.0,top: 12.rpx,right: 0.0,bottom: 12.rpx),
                                                    margin: EdgeInsets.symmetric(horizontal: 16.rpx),
                                                    decoration:  BoxDecoration(
                                                      //border: Border.all(width: 1.rpx,color: const Color(0xFFDCDCDC)),
                                                        border: Border(
                                                            bottom: BorderSide(
                                                                width: 0.5,
                                                                color: index == list.length -1?UIColor.color_content:const Color(0xFFDCDCDC)
                                                            )
                                                        )
                                                    ),
                                                    child: Row (
                                                        children: [
                                                          SizedBox(
                                                            width: 240.rpx,
                                                            child:  UText.get(list[index], UIColor.color_t5, 14.rpx),
                                                          ).expand,
                                                          currentActiveIndex == index? SvgPicture.asset(R.image_select,width: 24.rpx, height: 24.rpx):SvgPicture.asset(R.image_circle,width: 24.rpx, height: 24.rpx),
                                                        ]
                                                    )
                                                )
                                            )).toList()
                                        ),
                                        Container( height: 0.5.rpx, color: UIColor.color_divider),
                                        SizedBox(
                                            height: 58.rpx,
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                                              children: [
                                                Expanded(
                                                  child: TextButton(
                                                      onPressed: () {
                                                        Navigator.pop(context);
                                                      },
                                                      child: UText.get("取消", UIColor.color_t15, 16.rpx,fw: FontWeight.w600)
                                                  ),
                                                  flex: 1,
                                                ),
                                                Container(height: 58.rpx, width: 0.5.rpx, color: UIColor.color_divider),
                                                Expanded(
                                                  child:TextButton(
                                                      onPressed: () {
                                                        _cancel(data);
                                                      },
                                                      child: UText.get("确认", UIColor.color_primary, 16.rpx,fw: FontWeight.w600)
                                                  ),
                                                  flex: 1,
                                                ),
                                              ],
                                            )
                                        )
                                    ]
                                  )
                              )
                          );
                        }
                    );
                  }
                );
              },
              child:
                  // 2空闲中 5已完成 20已取消
                  data["status"] == 5 ||
                  data["status"] == 4 ||
                  data["status"] == 20 ||
                  total <= 1 ||
                  data["mission_status"] >= 5 ||
                  total - cancelTotal <= 1 ? 0.wspace:SvgPicture.asset(R.image_delete,width: 20.rpx,height: 24.rpx,)
            )
        ]
    );
  }

   _cancel(dynamic data) {
    var dialog = LoadingDialog(context);
    var json = _getPostJson();
    json["id"] = data["id"];
    json["reason"] = list[currentActiveIndex];
    dialog.show(text: "取消任务中...");
    var url = "/waybill_mission/cancel";
    Api.submitx(context, url, data: json,   progress: false, success: (data) {
      dialog.hide();
      Navigator.pop(context);
      _recyclerLayoutController.reload();
    }, failTip: "提交失败", fail: (_) {
      dialog.hide();
    });
  }

  _onClickSubmit() {
    var json = _getPostJson();
    json["waybill_no"] = widget.waybillNo;
    CustomAlertDialog.show(context, content: "确定新增任务吗？", onConfirm: () {
      var dialog = LoadingDialog(context);
      dialog.show(text: "提交中...");
      var url = "/waybill_mission/add";
      Api.submitx(context, url, data: json, progress: false, success: (data) {
        dialog.hide();
        _recyclerLayoutController.reload();
      }, failTip: "提交失败", fail: (_) {
        dialog.hide();
      });
    });
  }

  dynamic _getPostJson() {
    var json = {};
    return json;
  }

}